﻿using dal.cgm_production_dao;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using utils;

namespace create_ser
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            ConfigureDataGridView();
            versionLabel.Text = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

        }
        #region
        //private void buttonGenerate_Click(object sender, EventArgs e)
        //{
        //    string orderNumber = textBoxOrderNumber.Text;
        //    string productType = comboBoxProductType.Text;
        //    string memoryAddress = textBoxMemoryAddress.Text;
        //    string quantityText = textBoxQuantity.Text;

        //    string chipName = comboBoxChipName.Text;

        //    // 参数校验
        //    if (string.IsNullOrEmpty(orderNumber))
        //    {
        //        MessageBox.Show("制造令号不能为空或者空字符！");
        //        return;
        //    }

        //    if (!IsHexadecimal(memoryAddress) || memoryAddress.Length > 8 || !IsAddressWithinRange(memoryAddress, 0xFFFFFFFF))
        //    {
        //        MessageBox.Show("内存地址必须是有效的十六进制数，并且在 IC 支持的范围内！");
        //        return;
        //    }
        //    long addr = Convert.ToInt64(memoryAddress, 16);

        //    int macsCount = MacAddressPoolDao.MacsCount();
        //    if (macsCount == 0)
        //    {
        //        MessageBox.Show("mac地址已用完！");
        //        return;
        //    }

        //    if (!int.TryParse(quantityText, out int quantity) || quantity <= 0)
        //    {
        //        MessageBox.Show("生产数量必须是大于0的整数！");
        //        return;
        //    }
        //    if (quantity > macsCount)
        //    {
        //        MessageBox.Show("可使用Mac剩余" + macsCount + "不足" + quantity);
        //        return;
        //    }

        //    IList<MacAddressPool> macs = MacAddressPoolDao.GetMacs(quantity);

        //    if (macs.Count == 0)
        //    {
        //        MessageBox.Show("mac地址已用完！");
        //        return;
        //    }
        //    // 将 MAC 地址存储到 List<string> 中
        //    List<string> macAddresses = macs.Select(m => m.mac_address).ToList();

        //    //ser文件名称定义

        //    string unixTimestamp = Tool.ToUnixTimeSeconds(DateTime.UtcNow);

        //    //orderNumber_productType_memoryAddress_quantityText
        //    string filePath = orderNumber + "_" + productType + "_" + memoryAddress + "_" + quantityText + "_" + unixTimestamp + ".ser";

        //    int resCode = Tool.GenerateSerFile(macAddresses, filePath, addr, chipName);
        //    if (resCode == 500)
        //    {
        //        MessageBox.Show("系统繁忙稍后重试！");
        //        return;
        //    }

        //    MacAddressPoolDao.UpdateMacs(macAddresses);


        //    #region 弃用
        //    //// 生成 UsedMacInfo 对象
        //    //List<UsedMacInfo> usedMacInfos = macAddresses.Select((mac, index) => new UsedMacInfo
        //    //{
        //    //    order = orderNumber,
        //    //    model = productType,
        //    //    quantity = quantity,
        //    //    mac_address = mac,
        //    //    memory_addr = memoryAddress,
        //    //    create_time = DateTime.Now
        //    //}).ToList();
        //    //UsedMacInfoDao.InsertUsedMacInfos(usedMacInfos);
        //    #endregion

        //    MacAddressUsed aUsedMacInfo = new MacAddressUsed
        //    {
        //        order = orderNumber,
        //        model = productType,
        //        quantity = quantity,
        //        start_mac_address = macAddresses.First(),
        //        end_mac_address = macAddresses.Last(),
        //        memory_addr = memoryAddress,
        //        chip_name = chipName,
        //        create_time = DateTime.Now
        //    };

        //    MacAddressUsedDao.InsertMacAddressUsed(aUsedMacInfo);

        //    Console.WriteLine($"ser 文件已生成：{filePath}");

        //    // 提供下载路径
        //    MessageBox.Show($"ser 文件已生成：{filePath}\n文件路径：{Path.GetFullPath(filePath)}");

        //    // 可选：使用文件浏览器打开目录
        //    Process.Start("explorer.exe", $"/select,\"{Path.GetFullPath(filePath)}\"");
        //}
        #endregion
        private async void buttonGenerate_Click(object sender, EventArgs e)
        {
            string orderNumber = textBoxOrderNumber.Text;
            string productType = comboBoxProductType.Text;
            string memoryAddress = textBoxMemoryAddress.Text;
            string quantityText = textBoxQuantity.Text;

            string chipName = comboBoxChipName.Text;

            // 参数校验
            if (string.IsNullOrEmpty(orderNumber))
            {
                MessageBox.Show("制造令号不能为空或者空字符！");
                return;
            }

            if (!IsHexadecimal(memoryAddress) || memoryAddress.Length > 8 || !IsAddressWithinRange(memoryAddress, 0xFFFFFFFF))
            {
                MessageBox.Show("内存地址必须是有效的十六进制数，并且在 IC 支持的范围内！");
                return;
            }
            if (!int.TryParse(quantityText, out int quantity) || quantity <= 0)
            {
                MessageBox.Show("生产数量必须是大于0的整数！");
                return;
            }

            long addr = Convert.ToInt64(memoryAddress, 16);



            var client = new HttpClientHelper(ConfigurationManager.AppSettings["ServerUrl"]);

            // 示例：发送JSON请求
            var jsonRequest = new
            {
                product_type = productType,
                chip_name = chipName,
                order_number = orderNumber,
                memory_address = memoryAddress,
                quantity = int.Parse(quantityText),
                sc = "30b9c3ca5e9911ef9aa806433e9aa661",
                sv = "90bhc3ca5e9911ef9aa806433elaa668"
            };

            try
            {
                string jsonResponse = await client.PostJsonAsync("/api/GenerateSer", jsonRequest);

                var response = JsonConvert.DeserializeObject<ApiResponse>(jsonResponse);
                if (response.Code == 200)
                {

                    var res = JsonConvert.DeserializeObject<GenerateSerApiResponse>(jsonResponse);
                    List<string> macAddresses = res.Data.Select(m => m.MacAddress).ToList();

                    string unixTimestamp = Tool.ToUnixTimeSeconds(DateTime.UtcNow);

                    //orderNumber_productType_memoryAddress_quantityText
                    string filePath = orderNumber + "_" + productType + "_" + memoryAddress + "_" + quantityText + "_" + unixTimestamp + ".ser";

                    int resCode = Tool.GenerateSerFile(macAddresses, filePath, addr, chipName);
                    if (resCode == 500)
                    {
                        MessageBox.Show("系统繁忙稍后重试！");
                        return;
                    }

                    Console.WriteLine($"ser 文件已生成：{filePath}");

                    // 提供下载路径
                    MessageBox.Show($"ser 文件已生成：{filePath}\n文件路径：{Path.GetFullPath(filePath)}");

                    // 可选：使用文件浏览器打开目录
                    Process.Start("explorer.exe", $"/select,\"{Path.GetFullPath(filePath)}\"");
                }
                else
                {
                    MessageBox.Show(response.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool IsHexadecimal(string input)
        {
            const string hexPattern = @"\A\b[0-9a-fA-F]+\b\Z";
            return System.Text.RegularExpressions.Regex.IsMatch(input, hexPattern);
        }

        private bool IsAddressWithinRange(string address, long maxRange)
        {
            long addr = Convert.ToInt64(address, 16);
            return addr <= maxRange;
        }

        //private void buttonSelect_Click(object sender, EventArgs e)
        //{
        //    //string mac = textBoxMacSelect.Text;
        //    string productType = comboBoxSelect.Text;
        //    string orderNumber = textBoxOrderSelect.Text;

        //    if (string.IsNullOrEmpty(productType) && string.IsNullOrEmpty(orderNumber))
        //    {
        //        MessageBox.Show("至少一个查询条件不能为空！");
        //        return;
        //    }

        //    var usedMacInfos = MacAddressUsedDao.GetMacAddressUsed(productType, orderNumber);

        //    // 将查询结果绑定到 DataGridView
        //    dataGridViewResults.DataSource = usedMacInfos;

        //}

        private async void buttonSelect_Click(object sender, EventArgs e)
        {
            //string mac = textBoxMacSelect.Text;
            string productType = comboBoxSelect.Text;
            string orderNumber = textBoxOrderSelect.Text;

            if (string.IsNullOrEmpty(productType) && string.IsNullOrEmpty(orderNumber))
            {
                MessageBox.Show("至少一个查询条件不能为空！");
                return;
            }

            var client = new HttpClientHelper(ConfigurationManager.AppSettings["ServerUrl"]);

            // 示例：发送JSON请求
            var jsonRequest = new
            {
                product_type = productType,
                order_number = orderNumber,
                sc = "30b9c3ca5e9911ef9aa806433e9aa661",
                sv = "70b9c3ca9e9951ef9aa806433e9aa661"
            };

            try
            {
                string jsonResponse = await client.PostJsonAsync("/api/SerList", jsonRequest);

                var response = JsonConvert.DeserializeObject<ApiResponse>(jsonResponse);
                if (response.Code == 200)
                {
                    var res = JsonConvert.DeserializeObject<SerListApiResponse>(jsonResponse);

                    // 将查询结果绑定到 DataGridView
                    dataGridViewResults.DataSource = res.Data;

                }
                else
                {
                    MessageBox.Show(response.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            catch
            {
                MessageBox.Show("服务器内部错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dataGridViewResults_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            // 获取 DataGridView 控件本身
            DataGridView dgv = sender as DataGridView;

            using (SolidBrush b = new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor))
            {
                // 绘制行头文本，即序号
                e.Graphics.DrawString((e.RowIndex + 1).ToString(), dgv.RowHeadersDefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
            }
        }


       


        private void ConfigureDataGridView()
        {
            dataGridViewResults.AutoGenerateColumns = false;
            dataGridViewResults.RowHeadersWidth = 50; // 设置行头宽度以显示序号

            // 清除现有列
            dataGridViewResults.Columns.Clear();

            dataGridViewResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "Order",
                HeaderText = "制造令号",
                Name = "orderColumn"
            });

            dataGridViewResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "Model",
                HeaderText = "产品型号",
                Name = "modelColumn"
            });

            dataGridViewResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "ChipName",
                HeaderText = "芯片名称",
                Name = "chipNameColumn"
            });

            dataGridViewResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "StartMacAddress",
                HeaderText = "开始MAC",
                Name = "startmacAddressColumn"
            });

            dataGridViewResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "EndMacAddress",
                HeaderText = "结束MAC",
                Name = "endmacAddressColumn"
            });

            dataGridViewResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "Quantity",
                HeaderText = "生产数量",
                Name = "quantityColumn"
            });

            dataGridViewResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "MemoryAddr",
                HeaderText = "内存地址",
                Name = "memoryAddrColumn"
            });

            dataGridViewResults.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "CreateTime",
                HeaderText = "创建时间",
                Name = "createTimeColumn"
            });
        }

    }
}
